<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.addrole') }}</el-button>
    </div>
    <x-table ref="table" :headers="tableHeader" :list="list" />
    <el-dialog :title="$t(`table.${edit.textMap[edit.dialogStatus]}`)" :visible.sync="edit.dialogFormVisible">
      <el-form ref="dataForm" :rules="edit.rules" :model="edit.temp" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('table.roleName')" prop="roleName">
          <el-input v-model="edit.temp.roleName"/>
        </el-form-item>
        <el-form-item :label="$t('table.power')" prop="power">
          <el-checkbox-group v-model="edit.temp.power">
            <el-checkbox v-for="(item,index) in powerMap" :key="index" :label="item" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('table.use')" prop="status">
          <el-switch
            v-model="edit.temp.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item :label="$t('table.desc')" prop="desc">
          <el-input :autosize="{ minRows: 2, maxRows: 6}" v-model="edit.temp.desc" type="textarea" placeholder="Please input"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit.dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="edit.dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // 水波纹指令
import xTable from './table'
const powerMap = {
  admin: '管理员',
  editor: '编辑',
  root: '删库跑路'
}
export default {
  name: 'ComplexTable',
  components: {
    xTable
  },
  directives: {
    waves
  },
  filters: {

  },
  data() {
    return {
      list: null,
      total: null,
      powerMap: powerMap,
      tableKey: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      edit: {
        textMap: {
          update: 'editrole',
          create: 'addrole'
        },
        rules: {
          power: [{ required: true, message: 'title is required', trigger: 'change' }],
          roleName: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        temp: {
          id: null,
          roleName: '',
          status: 1,
          power: [],
          desc: ''
        },
        dialogStatus: 'create',
        dialogFormVisible: false
      },
      tableHeader: [
        {
          label: 'ID',
          width: 65,
          scope: 'id'
        },
        {
          tLabel: 'table.roleName',
          width: 150,
          scope: 'roleName'
        },
        {
          tLabel: 'table.power',
          width: 300,
          scope: row => {
            return row.power.name
          }
        }, {
          tLabel: 'table.desc',
          scope: 'desc'
        },
        {
          tLabel: 'table.status',
          width: 100,
          scope: 'status',
          className: 'status-col',
          tag: {
            type: row => {
              const statusMap = {
                1: 'success',
                2: 'danger'
              }
              return statusMap[row.status]
            },
            text: row => {
              const statusMap = {
                0: '已停用',
                1: '已启用'
              }
              return statusMap[row.status]
            }
          }
        },
        {
          tLabel: 'table.actions',
          width: 230,
          className: 'small-padding fixed-width',
          button: [
            {
              type: 'primary',
              click: this.handleUpdate,
              tText: 'table.edit'
            },
            {
              type: 'success',
              click: row => this.handleStatus(row, 1),
              tText: 'table.use',
              show: row => row.status === 0
            },
            {
              type: 'info',
              click: row => this.handleStatus(row, 0),
              tText: 'table.stopUse',
              show: row => row.status === 1
            },
            {
              type: 'danger',
              click: this.handleDelete,
              tText: 'table.delete'
            }
          ]
        }
      ]
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    powerFilter(status) {
      const arr = status.map(e => {
        return powerMap[e]
      })
      return {
        name: arr.join(','),
        arr,
        value: status
      }
    },
    getPowerVal(data) {
      const value = data.map(e => {
        for (const key in this.powerMap) {
          if (this.powerMap[key] === e) {
            return key
          }
        }
      })
      return value
    },
    getList() {
      this.$refs.table.loading(true)
      let arr = []
      for (var i = 1; i < 2; i++) {
        arr.push({
          id: i,
          roleName: '管理员',
          power: ['admin', 'editor', 'root'],
          desc: '拥有至高无上的权利',
          status: 1
        })
      }
      arr = arr.map(e => {
        e.power = this.powerFilter(e.power)
        return e
      })
      setTimeout(() => {
        this.$refs.table.append(arr)
        this.$refs.table.loading(false)
      }, 1000)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 修改状态
    handleStatus(row, status) {
      console.log(row, status)
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    // 删除列表
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    // 初始化
    resetTemp() {
      this.edit.temp = {
        id: null,
        roleName: '',
        status: 1,
        power: [],
        desc: ''
      }
    },
    // 点击新增
    handleCreate() {
      this.resetTemp()
      this.edit.dialogStatus = 'create'
      this.edit.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增data
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.edit.temp.power = this.powerFilter(this.getPowerVal(this.edit.temp.power))
          this.edit.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.list.push(this.edit.temp)
          this.edit.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 点击编辑
    handleUpdate(row) {
      this.edit.temp = Object.assign({}, row) // copy obj
      console.log(this.edit.temp)
      this.edit.temp.power = this.edit.temp.power.arr
      console.log(this.edit.temp)
      this.edit.dialogStatus = 'update'
      this.edit.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新data
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          for (const v of this.list) {
            if (v.id === this.edit.temp.id) {
              const index = this.list.indexOf(v)
              this.edit.temp.power = this.powerFilter(this.getPowerVal(this.edit.temp.power))
              this.list.splice(index, 1, this.edit.temp)
              break
            }
          }
          this.edit.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
